const app = getApp()

Page({
  data: {
    // 搜索相关
    searchValue: '',
    searchFocused: false,
    searching: false,
    
    // 搜索历史
    searchHistory: [],
    
    // 热门搜索
    hotSearches: [
      '麦当劳', '肯德基', '星巴克', '海底捞', '必胜客',
      '喜茶', '奶茶', '汉堡', '火锅', '烧烤',
      '川菜', '粤菜', '日料', '韩料', '西餐'
    ],
    
    // 搜索建议
    suggestions: [],
    showSuggestions: false,
    
    // 搜索结果
    searchResults: {
      stores: [],
      products: [],
      total: 0
    },
    
    // 搜索类型
    searchType: 'all', // all: 全部, store: 商家, product: 商品
    
    // 筛选条件
    filters: {
      category: 'all',
      priceRange: 'all',
      distance: 'all',
      rating: 'all'
    },
    
    // 排序方式
    sortType: 'default', // default: 默认, distance: 距离, rating: 评分, sales: 销量
    
    // 页面状态
    hasSearched: false,
    loading: false,
    loadingMore: false,
    hasMore: true,
    page: 1,
    pageSize: 20
  },

  onLoad(options) {
    const { keyword } = options
    
    if (keyword) {
      this.setData({
        searchValue: decodeURIComponent(keyword)
      })
      this.performSearch()
    }
    
    this.loadSearchHistory()
  },

  onShow() {
    // 页面显示时刷新搜索历史
    this.loadSearchHistory()
  },

  // 加载搜索历史
  loadSearchHistory() {
    try {
      const history = wx.getStorageSync('searchHistory') || []
      this.setData({
        searchHistory: history.slice(0, 10) // 最多显示10条
      })
    } catch (error) {
      console.error('加载搜索历史失败:', error)
    }
  },

  // 保存搜索历史
  saveSearchHistory(keyword) {
    if (!keyword || keyword.trim() === '') return
    
    try {
      let history = wx.getStorageSync('searchHistory') || []
      
      // 移除重复项
      history = history.filter(item => item !== keyword)
      
      // 添加到开头
      history.unshift(keyword)
      
      // 限制数量
      history = history.slice(0, 20)
      
      wx.setStorageSync('searchHistory', history)
      this.setData({
        searchHistory: history.slice(0, 10)
      })
    } catch (error) {
      console.error('保存搜索历史失败:', error)
    }
  },

  // 清空搜索历史
  clearSearchHistory() {
    wx.showModal({
      title: '确认清空',
      content: '确定要清空所有搜索历史吗？',
      success: (res) => {
        if (res.confirm) {
          try {
            wx.removeStorageSync('searchHistory')
            this.setData({
              searchHistory: []
            })
            wx.showToast({
              title: '已清空',
              icon: 'success'
            })
          } catch (error) {
            console.error('清空搜索历史失败:', error)
          }
        }
      }
    })
  },

  // 搜索输入
  onSearchInput(e) {
    const value = e.detail.value
    this.setData({
      searchValue: value
    })
    
    // 获取搜索建议
    if (value.trim()) {
      this.getSuggestions(value)
    } else {
      this.setData({
        suggestions: [],
        showSuggestions: false
      })
    }
  },

  // 搜索框聚焦
  onSearchFocus() {
    this.setData({
      searchFocused: true
    })
  },

  // 搜索框失焦
  onSearchBlur() {
    // 延迟隐藏建议，以便点击建议项
    setTimeout(() => {
      this.setData({
        searchFocused: false,
        showSuggestions: false
      })
    }, 200)
  },

  // 获取搜索建议
  async getSuggestions(keyword) {
    try {
      // 模拟搜索建议
      const mockSuggestions = [
        `${keyword}汉堡`,
        `${keyword}奶茶`,
        `${keyword}火锅`,
        `${keyword}烧烤`,
        `${keyword}川菜`
      ].filter(item => item !== keyword)
      
      this.setData({
        suggestions: mockSuggestions.slice(0, 5),
        showSuggestions: true
      })
    } catch (error) {
      console.error('获取搜索建议失败:', error)
    }
  },

  // 执行搜索
  async performSearch(keyword) {
    const searchKeyword = keyword || this.data.searchValue.trim()
    
    if (!searchKeyword) {
      wx.showToast({
        title: '请输入搜索关键词',
        icon: 'none'
      })
      return
    }
    
    this.setData({
      searchValue: searchKeyword,
      searching: true,
      loading: true,
      hasSearched: true,
      page: 1,
      hasMore: true,
      showSuggestions: false
    })
    
    // 保存搜索历史
    this.saveSearchHistory(searchKeyword)
    
    try {
      await this.searchData(searchKeyword, 1)
    } catch (error) {
      console.error('搜索失败:', error)
      wx.showToast({
        title: '搜索失败，请重试',
        icon: 'none'
      })
    } finally {
      this.setData({
        searching: false,
        loading: false
      })
    }
  },

  // 搜索数据
  async searchData(keyword, page = 1) {
    // 模拟搜索API
    const mockResults = await this.mockSearchAPI(keyword, page)
    
    if (page === 1) {
      this.setData({
        searchResults: mockResults,
        hasMore: mockResults.stores.length >= this.data.pageSize
      })
    } else {
      // 加载更多
      const currentResults = this.data.searchResults
      this.setData({
        searchResults: {
          ...currentResults,
          stores: [...currentResults.stores, ...mockResults.stores],
          products: [...currentResults.products, ...mockResults.products],
          total: mockResults.total
        },
        hasMore: mockResults.stores.length >= this.data.pageSize
      })
    }
    
    this.setData({
      page: page
    })
  },

  // 模拟搜索API
  mockSearchAPI(keyword, page) {
    return new Promise((resolve) => {
      setTimeout(() => {
        const mockStores = [
          {
            id: 1,
            name: `${keyword}餐厅(朝阳店)`,
            image: '/images/shop1.jpg',
            rating: 4.8,
            tags: ['快餐', '汉堡', '薯条'],
            distance: '1.2km',
            deliveryTime: '25分钟',
            deliveryFee: 3,
            isOpen: true,
            promotion: '满30减10'
          },
          {
            id: 2,
            name: `${keyword}小厨(三里屯店)`,
            image: '/images/shop2.jpg',
            rating: 4.6,
            tags: ['川菜', '麻辣', '下饭'],
            distance: '2.1km',
            deliveryTime: '35分钟',
            deliveryFee: 5,
            isOpen: true,
            promotion: '新用户立减5元'
          },
          {
            id: 3,
            name: `${keyword}工坊(国贸店)`,
            image: '/images/shop3.jpg',
            rating: 4.7,
            tags: ['烘焙', '甜品', '咖啡'],
            distance: '0.8km',
            deliveryTime: '20分钟',
            deliveryFee: 4,
            isOpen: true,
            promotion: '买二送一'
          }
        ]
        
        const mockProducts = [
          {
            id: 1,
            name: `${keyword}特色套餐`,
            price: 25.8,
            image: '/images/product1.jpg',
            storeName: '美味餐厅',
            sales: 1200
          },
          {
            id: 2,
            name: `招牌${keyword}`,
            price: 18.5,
            image: '/images/product2.jpg',
            storeName: '老字号小厨',
            sales: 800
          }
        ]
        
        resolve({
          stores: mockStores,
          products: mockProducts,
          total: mockStores.length + mockProducts.length
        })
      }, 1000)
    })
  },

  // 点击搜索建议
  onSuggestionTap(e) {
    const suggestion = e.currentTarget.dataset.suggestion
    this.performSearch(suggestion)
  },

  // 点击热门搜索
  onHotSearchTap(e) {
    const keyword = e.currentTarget.dataset.keyword
    this.performSearch(keyword)
  },

  // 点击搜索历史
  onHistoryTap(e) {
    const keyword = e.currentTarget.dataset.keyword
    this.performSearch(keyword)
  },

  // 删除搜索历史项
  deleteHistoryItem(e) {
    e.stopPropagation()
    const index = e.currentTarget.dataset.index
    const history = this.data.searchHistory
    history.splice(index, 1)
    
    this.setData({
      searchHistory: history
    })
    
    try {
      wx.setStorageSync('searchHistory', history)
    } catch (error) {
      console.error('删除搜索历史失败:', error)
    }
  },

  // 切换搜索类型
  switchSearchType(e) {
    const type = e.currentTarget.dataset.type
    this.setData({
      searchType: type
    })
    
    if (this.data.hasSearched) {
      this.performSearch()
    }
  },

  // 切换排序方式
  switchSortType(e) {
    const sortType = e.currentTarget.dataset.sort
    this.setData({
      sortType
    })
    
    if (this.data.hasSearched) {
      this.performSearch()
    }
  },

  // 跳转到商家详情
  goToStore(e) {
    const storeId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/store-detail/store-detail?id=${storeId}`
    })
  },

  // 跳转到商品详情
  goToProduct(e) {
    const productId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/product-detail/product-detail?id=${productId}`
    })
  },

  // 加载更多
  loadMore() {
    if (this.data.loadingMore || !this.data.hasMore) return
    
    this.setData({
      loadingMore: true
    })
    
    const nextPage = this.data.page + 1
    this.searchData(this.data.searchValue, nextPage).finally(() => {
      this.setData({
        loadingMore: false
      })
    })
  },

  // 清空搜索
  clearSearch() {
    this.setData({
      searchValue: '',
      hasSearched: false,
      searchResults: {
        stores: [],
        products: [],
        total: 0
      },
      suggestions: [],
      showSuggestions: false
    })
  },

  // 返回上一页
  goBack() {
    wx.navigateBack()
  },

  // 页面滚动到底部
  onReachBottom() {
    if (this.data.hasSearched) {
      this.loadMore()
    }
  },

  // 下拉刷新
  onPullDownRefresh() {
    if (this.data.hasSearched) {
      this.performSearch()
    }
    wx.stopPullDownRefresh()
  }
}) 